package com.qf.service.impl;

import com.qf.entity.Role;
import com.qf.service.PermissionService;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.Set;

public class PermissionServiceImpl implements PermissionService {



    @Override
    public Set<String> findAllPermsByRoleId(Set<Role> roles) {
        try {
            //1. 注册驱动
            Class.forName("com.mysql.jdbc.Driver");

            //2. 获取连接对象
            Connection connection = DriverManager.getConnection("jdbc:mysql:///shiro", "root", "root");

            //3. 声明SQL
            String sql =    "select " +
                            "  DISTINCT " +
                            "  p.perm_name permName " +
                            "from " +
                            "  permission p inner join roles_perms rp on p.id = rp.perm_id " +
                            "  inner join role r on r.id = rp.role_id " +
                            "where  " +
                            "  r.id in (";

            for (int i = 0; i < roles.size(); i++) {
                if(i != roles.size() - 1){
                    // 不是最后一次
                    sql += "?,";
                }else{
                    // 是最后一次
                    sql += "?)";
                }
            }



            //4. 预执行SQL，设置参数
            PreparedStatement ps = connection.prepareStatement(sql);
            int i = 1;
            for (Role role : roles) {
                ps.setObject(i,role.getId());
                i++;
            }

            //5. 执行SQL获取返回结果
            ResultSet rs = ps.executeQuery();
            Set<String> perms = new HashSet<>();
            //6. 遍历返回结果并封装对象
            while(rs.next()){
                perms.add(rs.getString("permName"));
            }
            //7. 释放资源
            rs.close();
            ps.close();
            connection.close();
            //8. 返回数据
            return perms;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
